# script sets infile, outfile, seqname before running

x = read.table(infile)
  
# Remove infinite values
lgl = is.finite(x[,2])
x = cbind(x[,1][lgl], x[,2][lgl])

# Log the data for the scatterplot?

logplot = T
tval = 100.
if (nrow(x) > 10) {
  fv = fivenum(abs(x[,2]))
  if (all(is.finite(fv))) {
    if (((fv[5]-fv[4]) / (fv[2]-fv[1]+1)) < tval) {
      logplot = F
    }
  }
}

signplot = any(x[,2] < 0)
if (any(x[,2] == 0)) {
  offset = 1
} else {
  offset = 0
}

# This assumes form.go has been changed to only specify width=600
if (logplot && signplot) {
  png(file=outfile, width=600, height=1200)
  par(mfcol=c(3,1), cex=1)
} else {
  png(file=outfile, width=600, height=800)
  par(mfcol=c(2,1))
}

seqlbl=paste(seqname,"(n)",sep="")

par(mar=c(5,5,2,2)+0.1)
k = min(200, nrow(x))
xsub = x[1:k,]
plot (xsub, 
  ylim = c(min(0, min(xsub[,2])), max(xsub[,2])),
  xlab = "n",
  ylab=seqlbl,
  bty="l",
  type="n",
  main = paste("Pin plot of", seqlbl))
segments(xsub[,1], rep(0, k), xsub[,1], xsub[,2])

if (logplot) {
  if (signplot) {
    signlbl=paste("|",seqlbl,"|",sep="")
  } else {
    signlbl=seqlbl
  }
  if (offset == 1) {
    offsetlbl=paste(signlbl,"+1",sep="")
  } else {
    offsetlbl=signlbl
  }

  par(mar=c(5,4,2,4)+0.1)
  plot(x[,1], log10(abs(x[,2])+offset), pch="+", cex=.5,
    xlab = "n",
    ylab=signlbl,
    main=paste("Logarithmic scatterplot of", signlbl),
    bty="o",yaxt="n")
  mtext(paste("log(",offsetlbl,")",sep=""),side=4,line=par("mgp")[1]);
  axis(side=4)
  ytk1=axTicks(side=4)
  ytk2=10^ytk1
  if (offset == 1 && ytk2[1] == 1.0) ytk2[1] = 0.0
  axis(side=2,at=log10(ytk2+offset),labels=ytk2)

  if (signplot) {
    plot(x[,1], asinh(x[,2]), pch="+", cex=.5,
      xlab = "n",
      ylab=seqlbl,
      main=paste("Logarithmic scatterplot of", seqlbl),
      bty="o",yaxt="n")
    mtext(paste("asinh(",seqlbl,")",sep=""),side=4,line=par("mgp")[1]);
    axis(side=4)
    ytk1=axTicks(side=4)/2
    ytk2=sign(ytk1)*10^abs(ytk1)
    axis(side=2,at=asinh(ytk2),labels=ytk2)
  }

} else {
  par(mar=c(5,5,2,2)+0.1)
  plot(x, pch="+", cex=.5,
    xlab = "n", 
    ylab = seqlbl,
    main = paste("Scatterplot of", seqlbl),
    bty="l")
}

dev.off()
